/**
 * 
 */
package com.ce.common.db.base;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 
 * @author chencao <a href="mailto:chencao0524@gmail.com">陈操</a>
 * 
 * @version $LastChangedRevision$ $LastChangedBy$ $LastChangedDate$
 * 
 */
public class PropertiesUtil {

	private static Properties prop = new Properties();

	private static String CONF = "/config/jdbc.properties";
	private static InputStream is = PropertiesUtil.class
			.getResourceAsStream(CONF);

	public static String JDBC_DRIVER;
	public static String JDBC_URL;
	public static String JDBC_USERNAME;
	public static String JDBC_PASSWD;
	public static String JDBC_HOST;
	public static String JDBC_DATABASE;
	public static String JDBC_URL_NO_CHECK;

	static {
		try {
			prop.load(is);
			JDBC_DRIVER = getProperty("jdbc.driverClassName");
			JDBC_URL = getProperty("jdbc.url");
			JDBC_USERNAME = getProperty("jdbc.username");
			JDBC_PASSWD = getProperty("jdbc.password");
			JDBC_HOST = getHost();
			JDBC_DATABASE = getDatabaseName();
			JDBC_URL_NO_CHECK = JDBC_URL + "&sessionVariables=FOREIGN_KEY_CHECKS=0";


		} catch (IOException e) {
			System.err.println("initial properties error!!");
			e.printStackTrace();
			System.exit(1);
		}
	}

	private static String getProperty(String key) {
		return prop.getProperty(key);
	}

	/**
	 * @return
	 */
	private static String getHost() {
		int beginIndex = JDBC_URL.trim().indexOf("jdbc:mysql://") + 13;
		int endIndex = JDBC_URL.trim().indexOf(":3306/");
		return JDBC_URL.trim().substring(beginIndex, endIndex);
	}

	/**
	 * @return
	 */
	private static String getDatabaseName() {
		int beginIndex = JDBC_URL.trim().indexOf("3306/") + 5;
		int endIndex = JDBC_URL.trim().indexOf("?") == -1 ? JDBC_URL.trim()
				.length() : JDBC_URL.trim().indexOf("?");
		return JDBC_URL.trim().substring(beginIndex, endIndex);
	}

	public static void main(String[] args) {
		System.out.println(getDatabaseName());
		System.out.println(JDBC_URL);
		System.out.println(JDBC_USERNAME);
		System.out.println(JDBC_PASSWD);
		System.out.println(JDBC_HOST);
		System.out.println(JDBC_DATABASE);
		System.out.println(JDBC_URL_NO_CHECK);
	}

}
